package com.syq.play.id3;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.syq.play.model.MediaModel;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;

public class Id3Util {
	private static Mp3ReadId3v1 id3v1;
	private static Mp3ReadId3v2 id3v2;

	public static MediaModel getMp3TAG(Context context, String path) {
		MediaModel media=new MediaModel();
		MediaPlayer mp=new MediaPlayer();
		String mediaData=path;
		String mediaTitle=null;
		String mediaArtist=null;
		String mediaAlbum=null;
		String mediaDuration=null;
		try {
			mp.setDataSource(path);
			mp.prepare();
			mediaDuration=(""+mp.getDuration());
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			id3v2 = new Mp3ReadId3v2(new FileInputStream(path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			id3v2.readId3v2(1024 * 100);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(id3v2.haveId3v2Tag()){
			mediaTitle=id3v2.getName();
			mediaArtist=id3v2.getAuthor();
			mediaAlbum=id3v2.getSpecial();
		}else{
			try {
				id3v1=new Mp3ReadId3v1(new FileInputStream(path));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			id3v1.readId3v1();
			mediaTitle=id3v1.getName();
			mediaArtist=id3v1.getAuthor();
			mediaAlbum=id3v1.getSpecial();
		}
		media.setMediaTitle(mediaTitle.trim());
		media.setMediaArtist(mediaArtist.trim());
		media.setMediaAlbum(mediaAlbum.trim());
		media.setMediaData(mediaData.trim());
		media.setMediaDuration(mediaDuration.trim());
		return media;
	}
	public static Bitmap getMp3Icon(String path){
		try {
			id3v2 = new Mp3ReadId3v2(new FileInputStream(path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			id3v2.readId3v2(1024 * 100);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(id3v2.getImg()==null){
			return null;
		}
		return BitmapFactory.decodeByteArray(id3v2.getImg(), 0, id3v2.getImg().length);
	}
}
